﻿namespace RFIDStation.DeviceDriver.IModules.Impls;

public class RFIDHFReaderModule : IModule
{
    private readonly ILogger _logger;
    private readonly ViewModel _viewModel;

    public RFIDHFReaderModule( ILoggerFactory loggerFactory, ViewModel viewModel )
    {
        _logger = loggerFactory.CreateLogger( "高频模块" );
        _viewModel = viewModel;
    }

    public async Task StartAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "hf" ) return;

        var config = _viewModel.AppConfig.RFIDReaderList.First( );

        _viewModel.RFIDHFReader = new Dev.Integration.HFReader.ApiClientBuilder( )
                                                              .UseReaderKind( config.Kind )
                                                              .UseReaderConfig( o =>
                                                              {
                                                                  o.Connect.ConnectType = config.ConnectType;
                                                                  o.Connect.ConnectArgs = config.ConnectArgs;
#if DEBUG
                                                                  o.MonitorLogAction = log => ConsoleWirter.Debug( $"+ [{DateTime.Now}] [hf] {log}" );
#endif
                                                              } )
                                                              .Build( );

        _viewModel.RFIDHFReader.OnOpenedHandler = ( s, e ) =>
        {
            ConsoleWirter.Success( $"+ [hf] {_viewModel.RFIDHFReader.ReaderId} 连接成功" );
        };

        // 重连机制
        _ = Task.Factory.StartNew( ( ) =>
        {
            while ( true )
            {
                try
                {
                    if ( _viewModel.RFIDHFReader.ReaderState == Dev.Integration.HFReader.Constants.ReaderState.Close )
                    {
                        _viewModel.RFIDHFReader.Open( );
                    }
                }
                catch ( Exception ex )
                {
                    ConsoleWirter.Warning( $"+ [hf] {_viewModel.RFIDHFReader.ReaderConfig.Connect.ConnectArgs} 连接失败: {ex.Message}" );
                }

                Thread.Sleep( 10 * 1000 );
            }
        } );

        await Task.CompletedTask;
    }

    public async Task StopAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "hf" ) return;

        try
        {
            _viewModel.RFIDHFReader.Close( );

            _logger.Info( $"注销成功. 读写器: {_viewModel.RFIDHFReader.ReaderId}" );
        }
        catch ( Exception ex )
        {
            _logger.Warning( $"注销失败. 读写器: {_viewModel.RFIDHFReader.ReaderId}{Environment.NewLine}error: {ex.Message}" );
        }

        await Task.CompletedTask;
    }
}
